from ..original.pickup import PickupAPI
import math


class Pickup(object):

    @classmethod
    def address(cls,
                name: str,
                company_name: str,
                country: str,
                state: str,
                city: str,
                street: str,
                postal_code: str,
                phone: str,
                email: str
                ) -> dict:
        """
        封装地址
        :param name: 姓名
        :param company_name:  公司名称
        :param country: 国家
        :param state: 省份
        :param city: 城市
        :param street: 街道
        :param postal_code: 邮编
        :param phone: 电话
        :param email: 邮箱
        """
        return {"name": name,
                "company_name": company_name if company_name else '',
                "street1": street if street else '',
                "street2": "",
                "city": city if city else '',
                "state": state if state else '',
                "postal_code": postal_code if postal_code else '',
                "country": country if country else '',
                "phone": phone if phone else '',
                "email": email if email else ''}

    @classmethod
    def parcels(cls, parcels_list: list, ) -> dict:
        """
        封装包裹
        :param parcels_list: 包裹内容明细，内容与封装结构：
               [{"length": 5,"width": 5,"height": 5,"weight": 10},...]
               parcel_id,parcel_type 不是必填
        """
        parcels = []
        for p in parcels_list:
            p_line = {"length": p['length'],
                      "width": p['width'],
                      "height": p['height'],
                      "weight": p['weight']}
            parcels.append(p_line)
        return {'parcels': parcels}

    @classmethod
    def book_pickup(cls, address: dict,
                    receive_country: str,
                    parcels: dict,
                    courier_name: str,
                    courier_service_code: int,
                    book_timestamp: float,
                    book_note: str):
        """
        预约上门取件
        :param address: 发件人地址信息
        :param receive_country:发件人国家代码
        :param parcels:包裹明细[{"length": 5,"width": 5,"height": 5,"weight": 10}]
        :param courier_name:承运商名称
        :param courier_service_code:ShipPyPro中承运商服务编码
        :param book_timestamp:预约时间（时间戳）
        :param book_note:预约描述
        :return {'message':'成功描述',
                 'confirmation_id':'ShipPyPro预约号',
                 'classify':'级别',
                 'validation_errors':'合法性错误检验(可能有)'} or '错误原因'
        """
        try:
            response = PickupAPI.book_pickup(send_name=address['name'],
                                             send_company_name=address['company_name'],
                                             send_phone=address['phone'],
                                             send_email=address['email'],
                                             send_country=address['country'],
                                             send_state=address['state'],
                                             send_city=address['city'],
                                             send_street=address['street1'],
                                             send_postal_code=address['postal_code'],
                                             receive_country=receive_country,
                                             parcels_list=parcels['parcels'],
                                             courier_name=courier_name,
                                             courier_service_code=courier_service_code,
                                             book_timestamp=int(math.floor(book_timestamp)),
                                             book_note=book_note if book_note else ' ')
            flag = response.get('Result')
            if flag == 'OK':
                result = {'message': response['Message'],
                          'confirmation_id': response['ConfirmationID']['0'],
                          'classify': response['ConfirmationID']['@attributes']['tipo']}
                if response.get('ValidationErrors', False):
                    result.update({'validation_errors': response['ValidationErrors']})
                return True, result
            else:
                return False, "连接失败，失败原因：{}".format(response['Message'])
        except Exception as e:
            return False, '调用接口失败，失败原因：{}'.format(e)

    @classmethod
    def cancel_pickup(cls,
                      courier_name: str,
                      courier_service_code: int,
                      confirmation_number: str,
                      book_timestamp: float):
        """
        取消预约上门取件
        :param courier_name:承运商名称
        :param courier_service_code:ShipPyPro中承运商服务编码
        :param confirmation_number: ShipPyPro中预约代码
        :param book_timestamp:预约时间（时间戳）
        :return {'message':'成功描述'} or '错误原因'
        """
        try:
            response = PickupAPI.cancel_pickup(courier_name=courier_name,
                                               courier_service_code=courier_service_code,
                                               confirmation_code=confirmation_number,
                                               book_timestamp=int(math.floor(book_timestamp)))
            flag = response.get('Result')
            if flag == 'OK':
                result = {'message': '取消预约成功'}
                return True, result
            else:
                return False, "连接失败，失败原因：{}".format(response['Message'])
        except Exception as e:
            return False, '调用接口失败，失败原因：{}'.format(e)
